<template>
    <div class="app-container compact-layout">
      <!-- 加载遮罩 -->
      <div v-if="loading" class="loading-overlay">
        <el-icon class="is-loading" style="font-size: 32px;">
          <Loading />
        </el-icon>
      </div>

     <!-- 补货方案设置卡片 -->
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>智能补货设置</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              @click="checkStockWarning">
              检查库存预警
            </el-button>
          </div>

           <!-- 添加预警商品表格 -->
                <el-table
                  :data="warningItems"
                  border
                  style="width: 100%; margin-bottom: 20px"
                  v-if="warningItems.length > 0">
                  <el-table-column prop="goodsName" label="商品名称"></el-table-column>
                  <el-table-column prop="warehouseName" label="仓库"></el-table-column>
                  <el-table-column prop="currentStock" label="当前库存">
                    <template #default="{row}">
                      {{ row.inQuantity - row.outQuantity }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="warningValue" label="预警值"></el-table-column>
                  <el-table-column label="补货数量">
                    <template #default="{row}">
                      <el-input-number
                        v-model="row.replenishQuantity"
                        :min="1"
                        size="mini"
                        placeholder="数量">
                      </el-input-number>
                    </template>
                  </el-table-column>
                </el-table>

      <div class="replenishment-settings">
        <el-form :model="replenishForm" label-width="90px" size="small">
          <!-- 商品选择 -->
          <el-form-item label="商品范围" prop="selectedGoods" required>
            <el-row :gutter="8" type="flex" align="middle">
              <el-col :span="6">
                <el-select
                  v-model="replenishForm.selectedGoods"
                  multiple
                  placeholder="商品"
                  filterable
                  clearable
                  style="width:100%"
                  class="uniform-select"
                  :loading="goodsLoading"
                >
                  <el-option
                    v-for="item in goodsOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-cascader
                  v-model="replenishForm.selectedCategories"
                  :options="categoryOptions"
                  :props="cascaderProps"
                  placeholder="类别"
                  style="width:100%"
                  :loading="categoryLoading"
                />
              </el-col>
            </el-row>
          </el-form-item>

          <!-- 仓库选择 -->
          <el-form-item label="仓库" prop="warehouseId" required>
            <el-select
              v-model="replenishForm.warehouseId"
              placeholder="请选择仓库"
              style="width: 100%;"
              :loading="warehouseLoading"
            >
              <el-option
                v-for="warehouse in warehouseOptions"
                :key="warehouse.id"
                :label="warehouse.name"
                :value="warehouse.id"
              />
            </el-select>
          </el-form-item>

          <!-- 最低库存 -->
          <el-form-item label="最低库存" prop="minStock">
            <el-input v-model="replenishForm.minStock" type="number" placeholder="请输入最低库存"/>
          </el-form-item>

          <!-- 安全库存 -->
          <el-form-item label="安全库存" prop="safetyStock">
            <el-input v-model="replenishForm.safetyStock" type="number" placeholder="请输入安全库存"/>
          </el-form-item>

          <!-- 是否包含库存需求 -->
          <el-form-item label="包含库存需求" prop="includeStockDemand">
            <el-switch v-model="replenishForm.includeStockDemand"/>
          </el-form-item>

          <!-- 是否包含销售预测 -->
          <el-form-item label="包含销售预测" prop="includeSalesForecast">
            <el-switch v-model="replenishForm.includeSalesForecast"/>
          </el-form-item>

           <!-- 生成采购计划按钮 -->
                    <el-form-item>
                      <el-button
                        type="primary"
                        @click="generatePurchasePlan"
                        :disabled="warningItems.length === 0">
                        生成采购计划
                      </el-button>
                      <el-button
                        type="warning"
                        @click="autoGeneratePlan"
                        :loading="autoGenerating">
                        自动生成补货计划
                      </el-button>
                    </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { Loading } from 'element-ui';
import { listCategory } from '@/api/goods/category';
import { listGoods } from "@/api/goods/goods";
import { listWarehouse } from "@/api/system/warehouse";
import { listWarehouseStock } from "@/api/system/warehouseStock";
import { addPlan, listPlan } from "@/api/procurementmanagement/plan";

export default {
  name: 'ReplenishmentSettings',
  components: {
    Loading
  },
  data() {
    return {
      warningItems: [],
      autoGenerating: false,
      loading: false,
      goodsLoading: false,
      categoryLoading: false,
      warehouseLoading: false,
      replenishForm: {
        selectedGoods: [],
        selectedCategories: [],
        warehouseId: null,
        minStock: 0,
        safetyStock: 0,
        includeStockDemand: false,
        includeSalesForecast: false
      },
      goodsOptions: [],
      categoryOptions: [],
      cascaderProps: {
        label: 'name',
        value: 'categoryId',  // 根据API响应改为categoryId
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      warehouseOptions: [],
      goodsList: []
    };
  },
  methods: {
    // ...其他方法保持不变

    // 修改获取商品列表方法
    async getGoodsList() {
      this.goodsLoading = true;
      try {
        const response = await listGoods();
        if (response && response.code === 200 && response.rows) {
          this.goodsOptions = response.rows.map(item => ({
            id: item.id,  // 根据API响应使用id
            name: item.name  // 根据API响应使用name
          }));
        } else {
          this.$message.warning('商品列表数据为空');
          this.goodsOptions = [];
        }
      } catch (error) {
        console.error('获取商品列表失败:', error);
        this.$message.error('获取商品列表失败: ' + (error.response?.data?.message || error.message || '服务器错误'));
        this.goodsOptions = [];
      } finally {
        this.goodsLoading = false;
      }
    },

    // 修改获取类别列表方法
    async getCategoryList() {
      this.categoryLoading = true;
      try {
        const response = await listCategory();
        if (response && response.code === 200 && response.rows) {
          // 根据API响应数据构建树形结构
          const categories = response.rows;

          // 找出所有顶级分类(parentId === 0)
          const topLevelCategories = categories.filter(cat => cat.parentId === 0);

          // 递归构建树形结构
          const buildTree = (parentId) => {
            return categories
              .filter(cat => cat.parentId === parentId)
              .map(cat => ({
                categoryId: cat.categoryId,
                name: cat.name,
                children: buildTree(cat.categoryId)
              }));
          };

          this.categoryOptions = topLevelCategories.map(cat => ({
            categoryId: cat.categoryId,
            name: cat.name,
            children: buildTree(cat.categoryId)
          }));
        } else {
          this.$message.warning('类别列表数据为空');
          this.categoryOptions = [];
        }
      } catch (error) {
        console.error('获取类别列表失败:', error);
        this.$message.error('获取类别列表失败: ' + (error.response?.data?.message || error.message || '服务器错误'));
        this.categoryOptions = [];
      } finally {
        this.categoryLoading = false;
      }
    },

    // 检查库存预警
        async checkStockWarning() {
          this.loading = true;
          try {
            const response = await listWarehouseStock({ warningFilter: true });
            if (response.rows && response.rows.length > 0) {
              this.warningItems = response.rows.map(item => ({
                ...item,
                currentStock: item.inQuantity - item.outQuantity,
                replenishQuantity: this.calculateReplenishQuantity(item)
              }));
              this.$message.success(`发现 ${response.rows.length} 个商品需要补货`);
            } else {
              this.warningItems = [];
              this.$message.success('当前没有需要补货的商品');
            }
          } catch (error) {
            this.$message.error('获取库存预警失败: ' + error.message);
          } finally {
            this.loading = false;
          }
        },

        // 自动生成补货计划
            async autoGeneratePlan() {
              this.autoGenerating = true;
              try {
                await this.checkStockWarning();
                if (this.warningItems.length > 0) {
                  await this.generatePurchasePlan();
                }
              } finally {
                this.autoGenerating = false;
              }
            },

    // 在 methods 中添加
    async generatePurchasePlan() {
      this.loading = true;
      try {
        // 1. 获取低于库存预警的商品
        const warningResponse = await listWarehouseStock({
          warningFilter: true
        });

        if (!warningResponse.rows || warningResponse.rows.length === 0) {
          this.$message.success('当前没有需要补货的商品');
          return;
        }

        // 2. 生成计划编号
        const planNumber = await this.generateAutoPlanNumber();

        // 3. 准备补货计划数据
        const planData = {
          sn: planNumber, // 使用生成的计划编号
          deptId: 4, // 固定使用采购部门ID=4
          deptName: '采购部', // 固定部门名称
          formationPersonId: 1, // 当前用户ID
          formationPerson: '管理员', // 当前用户姓名
          formationTime: new Date().toISOString().slice(0, 10), // 当前日期
          procurementDesc: '智能补货计划 - 库存预警自动生成',
          supplierId: this.getDefaultSupplierId(), // 获取默认供应商ID
          supplierName: this.getDefaultSupplierName(), // 获取默认供应商名称
          supplierTime: this.calculateDefaultSupplyTime(), // 计算默认供应时间
          productList: warningResponse.rows.map(item => ({
            goodsId: item.goodsId,
            goodsName: item.goodsName,
            goodsSn: item.goodsSn,
            specification: item.specification,
            categoryId: item.categoryId,
            categoryName: item.categoryName,
            procurementNum: this.calculateReplenishQuantity(item),
            remark: '库存预警自动补货',
            supplyTime: this.calculateDefaultSupplyTime(),
            costPrice: item.costPrice || 0,
            taxRate: item.taxRate || 0
          }))
        };

        // 4. 提交补货计划
        const response = await addPlan(planData);
        if (response.code === 200) {
          this.$message.success('补货计划生成成功');
          // 刷新计划列表
          this.$emit('plan-generated');
        } else {
          this.$message.error('补货计划生成失败: ' + response.msg);
        }
      } catch (error) {
        console.error('生成补货计划失败:', error);
        this.$message.error('生成补货计划失败: ' + (error.response?.data?.message || error.message || '服务器错误'));
      } finally {
        this.loading = false;
      }
    },

    // 生成自动计划编号
      async generateAutoPlanNumber() {
        const prefix = "PL"; // 计划前缀
        const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, ""); // 格式化为YYYYMMDD

        try {
          // 获取当天已有的计划数量
          const count = await this.getPlanCountByDate(new Date().toISOString().slice(0, 10));
          const seq = count + 1; // 序列号从1开始
          const formattedSeq = String(seq).padStart(4, "0"); // 格式化为4位数字
          return `${prefix}${dateStr}${formattedSeq}`;
        } catch (error) {
          console.error('生成计划编号失败:', error);
          // 如果获取数量失败，使用时间戳作为后备方案
          const timestamp = new Date().getTime().toString().slice(-4);
          return `${prefix}${dateStr}${timestamp}`;
        }
      },

      // 获取当天计划数量的方法
      async getPlanCountByDate(date) {
        try {
          const response = await listPlan({ formationTime: date });
          return response.total || 0;
        } catch (error) {
          console.error('获取计划数量失败:', error);
          return 0; // 如果失败，默认返回0
        }
      },
      // 获取默认供应商ID (可根据实际业务调整)
      getDefaultSupplierId() {
        return 1; // 默认供应商ID，可以从配置或API获取
      },

      // 获取默认供应商名称
      getDefaultSupplierName() {
        return "食品生产有限公司"; // 可以从配置或API获取
      },

      // 计算默认供应时间 (当前日期+7天)
      calculateDefaultSupplyTime() {
        const date = new Date();
        date.setDate(date.getDate() + 7);
        return date.toISOString().slice(0, 10);
      },

    // 计算补货数量
    calculateReplenishQuantity(item) {
      const currentStock = item.inQuantity - item.outQuantity;
      const safetyStock = this.replenishForm.safetyStock || 10;
      const minStock = this.replenishForm.minStock || 5;

      // 计算需要补货的数量
      return Math.max(safetyStock - currentStock, minStock);
    },

    // 修改获取仓库列表方法
    async getWarehouseList() {
      this.warehouseLoading = true;
      try {
        const response = await listWarehouse();
        if (response && response.code === 200 && response.rows) {
          this.warehouseOptions = response.rows.map(item => ({
            id: item.id,  // 根据API响应使用id
            name: item.name  // 根据API响应使用name
          }));
        } else {
          this.$message.warning('仓库列表数据为空');
          this.warehouseOptions = [];
        }
      } catch (error) {
        console.error('获取仓库列表失败:', error);
        this.$message.error('获取仓库列表失败: ' + (error.response?.data?.message || error.message || '服务器错误'));
        this.warehouseOptions = [];
      } finally {
        this.warehouseLoading = false;
      }
    }
  },
  created() {
    this.getGoodsList();
    this.getCategoryList();
    this.getWarehouseList();
  }
};
</script>

<style scoped>
/* 原有样式保持不变 */
.app-container {
  padding: 20px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.box-card {
  margin-bottom: 20px;
}

.replenishment-settings {
  padding: 20px;
}

/* 统一选择框样式 */
.uniform-select {
  height: 32px;
  line-height: 32px;
}

/* 调整表单标签对齐 */
.el-form-item__label {
  line-height: 32px;
}

/* 确保输入框和选择框对齐 */
.el-input__inner, .el-cascader .el-input__inner {
  height: 32px;
  line-height: 32px;
}

/* 调整多选框对齐 */
.el-checkbox {
  line-height: 32px;
}

/* 调整数字输入框对齐 */
.el-input-number {
  line-height: 30px;
}

/* 统一行内元素垂直对齐 */
.el-row--flex {
  align-items: center;
}

/* 按钮样式调整 */
.el-button {
  margin-top: 10px;
}
</style>
